﻿/*
 *Author: Jeff Liu 
 *
 *Under MIT License
 *jebberwocky@gmail.com
 *
 * Notice: this is only a "simple" program to demostrate how to use Google Geo Kit. It is not perfomance turned nor code refined
 * for any furthur question, please mail to jebberwocky@gmail.com, glad to answer your question
 */
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CtpGgglMapWinUI.Cache;
using System.Drawing;

namespace Citiport.Demo.Cache
{
    public sealed class AppMapCache: IMapImageCache
    {

        #region IMapImageCache Members

        static AppMapCache instance = null;

        static readonly object padlock = new object();

        static Dictionary<String, Image> caches = new Dictionary<string, Image>();

        const int MAX_POOL_SIZE = 500;

        static AppMapCache()
        {
        }

        AppMapCache()
        {
        }

        public static AppMapCache Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new AppMapCache();
                    }
                    return instance;
                }
            }
        }

        public void Clean()
        {
            caches = new Dictionary<string, Image>();
        }

        public System.Drawing.Image GetImage(string key)
        {
            if (caches.Keys.Contains(key))
            {
                Console.WriteLine(string.Format("get cached image with key:{0}", key));
                return new Bitmap(caches[key]);
            }
            else
                return null;
        }

        public void SetImage(System.Drawing.Image image, string key)
        {
            if (!caches.Keys.Contains(key))
            {
                if (caches.Count >= MAX_POOL_SIZE)
                {
                    String first = caches.Select(x => x.Key).FirstOrDefault();
                    if (first != null)
                    {
                        Console.WriteLine(string.Format("remove cached image with key:{0}", first));
                        // dispose the cache copy then remove
                        caches[key].Dispose();
                        caches.Remove(first);
                    }
                }
                Console.WriteLine(string.Format("set cached image with key:{0}", key));
                //keep cache copy
                caches[key] = new Bitmap(image);
            }
        }
        #endregion
    }
}
